package fatworm.concept.datatype;

public class FatDecimal extends fatworm.concept.DataType{
	
	public static FatDecimal createInstance( int mLength , int dLength ){
		return new FatDecimal( mLength , dLength );
	}
	
	private int mLength , dLength;

	private FatDecimal( int mLength , int dLength ){
		this.mLength = mLength; this.dLength =  dLength;
 	}
	public String toString(){
		return "DECIMAL("+mLength +","+dLength+")"; 
	}
	
	public int getMaxLength() {
		return mLength + dLength + 1;
	}
	
	public DecimalValue createValue( String value ) 
		throws java.lang.IllegalArgumentException {
		if( value.length() > mLength ) throw new java.lang.IllegalArgumentException();
		if( value.contains(".")){
			String parts[] = value.split("\\.");
			if( parts.length == 2 && parts[0].matches("[0-9]+") 
					&& parts[1].length() <= dLength && parts[1].matches("[0-9]+") ){
						return new DecimalValue( parts[0] , parts[1] );
			}
			
		}
		else{
			if( value.matches("[0-9]+") && value.length() > mLength - dLength )
				return new DecimalValue( value,"");
		}
	
		throw new java.lang.IllegalArgumentException();
	}
	
	public DecimalValue convert(SqlValue value) throws ConvertException {
		switch( value.getType().getTypeKey() ){
			case T_STRING :
			case T_DECIMAL:
				try{
					return  createValue( value.toString() );
				}catch( java.lang.IllegalArgumentException e){
					e.printStackTrace();
					throw new ConvertException( value , this );
				}
			default	: throw new ConvertException( value , this );
		}
	}
	public int getTypeKey() {
		return T_DECIMAL;
	}
	public class DecimalValue extends SqlValue{
		public String first,second;			
		private DecimalValue( String first , String second ) {
			this.first = first; this.second = second;
		}
		public String toString() {
			return first + (second.isEmpty() ?"" : "."+second) ;
		}
		
	}
}
